import React, { Component } from 'react'

import 'bootstrap/dist/css/bootstrap.min.css'
import PriceList from "../components/PriceList"
import ViewTab from "../components/ViewTab";
import {LIST_VIEW, TYPE_INCOME, TYPE_OUTCOME, parseToYearAndMonth, items, categories, CHART_VIEW,newItem,padLeft} from "../utility";
import TotalPrices from "../components/TotalPrices";
import MonthPicker from "../components/MonthPicker";
import CreateBtn from "../components/CreateBtn";



class Home extends Component{
  constructor(props) {
    super(props);
    this.state = {
      items,
      currentDate: parseToYearAndMonth(),
      tabView: LIST_VIEW
    }
  }

  changeView = (view)=>{
    this.setState(
      {
        tabView:view
      }
    )
  }

  changeDate=(year,month)=>{
         this.setState({
           currentDate:{year,month}
         })
  }

  modifyItem = (modifiedItem)=>{
    const modifiedItems = this.state.items.map(item=>{
      if (item.id===modifiedItem.id){
        return {...item,title:"新的标题"}
      }else {
        return item
      }
    })
    this.setState(
      {
        items:modifiedItems
      }
    )
  }

  createItem = ()=>{
  this.setState(
    {
       items:[newItem,...this.state.items]
    }
  )
  }

  deleteItem = (deletedItem)=>{
    console.log(deletedItem);
    const filterItems = this.state.items.filter(item=>item.id !==deletedItem.id)
    this.setState(
      {
        items:filterItems
      }
    )
  }

render() {
    let totalIncome = 0, totalOutcome = 0
    const {items,currentDate,tabView} = this.state
   const itemsWithCatory = items.map((item)=>{
     item.category = categories[item.cid]
     return item
   })

  itemsWithCatory.forEach(item=>{
    if(item.category.type===TYPE_OUTCOME){
      totalOutcome+=item.price
    }else {
      totalIncome+=item.price
    }
    }

  )
  return(
    <React.Fragment>
      <header className="App-header">
        <div className="row">
          <div className="col">
            <MonthPicker
              year={currentDate.year}
              month={currentDate.month}
              onChange={this.changeDate}
            />

          </div>
          <div className="col">
            <TotalPrices
              income={totalIncome}
              outcome={totalOutcome}
            />
          </div>
        </div>

      </header>
      <div className="content-area p y-3 px-3">
        <ViewTab
          activateTab={tabView}
          onTabChange={this.changeView}
        />

        <CreateBtn onClick={this.createItem}/>
        {
          tabView === LIST_VIEW &&
          <PriceList
            items = {itemsWithCatory}
            onModifyItem={this.modifyItem}
            onDeleteItem={this.deleteItem }
          />
        }
        {
          tabView===CHART_VIEW &&
            <h1>这里是图表</h1>
        }


      </div>
    </React.Fragment>
  )
}

}

export default Home